package com.tianji.promotion.lock;

import com.tianji.common.exceptions.BizIllegalException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class LockFactory {

    @Autowired
    private RedissonClient redissonClient;

    private Map<LockType, Function<String, RLock>> map = new HashMap<>(){
        {
            put(LockType.LOCK, (lockName)->redissonClient.getLock(lockName));
            put(LockType.FAIR_LOCK, (lockName)->redissonClient.getFairLock(lockName));
            put(LockType.READ_LOCK, (lockName)->redissonClient.getReadWriteLock(lockName).readLock());
            put(LockType.WRITE_LOCK, (lockName)->redissonClient.getReadWriteLock(lockName).writeLock());
        }
    };

    public RLock getLock(LockType lockType, String lockName){
        Function<String, RLock> function = map.get(lockType);
        if(function == null){
            throw new BizIllegalException("不支持的锁的类型");
        }
        return function.apply(lockName);
    }
}